package com.suyx.job.controller;

import java.util.Date;

import com.suyx.job.entity.JobInfo;
import com.suyx.job.entity.Result;
import com.suyx.job.service.IJobInfoService;
import com.suyx.job.utils.SchedulerUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping(value = "/job")
public class JobController {

    private SchedulerUtils scheduler;

    private IJobInfoService jobInfoService;

    @Autowired
    public JobController(SchedulerUtils scheduler, IJobInfoService jobInfoService) {
        this.scheduler = scheduler;
        this.jobInfoService = jobInfoService;
    }


    @GetMapping(value = "/findJobAll")
    public Object findJobAll(JobInfo jobInfo, Integer page, Integer limit) {
        return jobInfoService.findJobPage(jobInfo, page - 1, limit);
    }

    @PostMapping(value = "/addJob")
    public Result addJob(JobInfo jobInfo) {
        if (jobInfoService.existsByJobNameAndJobGroup(jobInfo.getJobName(), jobInfo.getJobGroup())) {
            return new Result(false, "该任务名称已被使用！");
        }
        jobInfo.setCreateDate(new Date());
        jobInfo.setUpdateDate(new Date());
        try {
            jobInfoService.save(jobInfo);
            if (jobInfo.getJobStatus() == 0) {
                scheduler.addJob(jobInfo);
            }
            return new Result(true, "新增成功！");
        } catch (Exception e) {
            log.error("新增定时任务出现异常！" + ExceptionUtils.getStackTrace(e));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//捕获异常后进行回滚
            return new Result(false, "新增失败！" + e.getMessage());
        }
    }

    @PostMapping(value = "/updateJob")
    public Result updateJob(JobInfo jobInfo) {
        try {
            JobInfo jobInfo1 = jobInfoService.findById(jobInfo.getJobId()).get();
            jobInfo1.setUpdateDate(new Date());
            jobInfo1.setEmailServerId(jobInfo.getEmailServerId());
            jobInfo1.setIntroduce(jobInfo.getIntroduce());
            jobInfo1.setEmailType(jobInfo.getEmailType());
            jobInfo1.setExecuteAddress(jobInfo.getExecuteAddress());
            jobInfo1.setCronExpression(jobInfo.getCronExpression());
            jobInfo1.setExecuteType(jobInfo.getExecuteType());
            // 修改job 状态、运行class
            if (!jobInfo.getJobStatus().equals(jobInfo1.getJobStatus())
                    || !jobInfo.getClassPath().equals(jobInfo1.getClassPath())) {
                jobInfo1.setClassPath(jobInfo.getClassPath());
                jobInfo1.setJobStatus(jobInfo.getJobStatus());
                scheduler.updateStatus(jobInfo1);
            }
            // 状态为0 正在运行 则 修改job信息
            if (jobInfo.getJobStatus().intValue() == 0) {
                scheduler.jobReschedule(jobInfo1);
            }
            jobInfoService.saveAndFlush(jobInfo1);
            return new Result(true, "修改成功！");
        } catch (Exception e) {
            log.error("修改定时任务出现异常！" + ExceptionUtils.getStackTrace(e));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//捕获异常后进行回滚
            return new Result(false, "修改失败！" + e.getMessage());
        }
    }

    @PostMapping(value = "/updateStatus")
    public Result updateStatus(Integer jobId, Integer jobStatus) {
        try {
            JobInfo jobInfo = jobInfoService.getOne(jobId);
            if (jobInfo == null) {
                return new Result(false, "该id值不存在！操作失败");
            }
            jobInfo.setJobStatus(jobStatus);
            jobInfoService.saveAndFlush(jobInfo);
            scheduler.updateStatus(jobInfo);
            return new Result(true, "操作成功！");
        } catch (Exception e) {
            log.error("停用定时任务出现异常！" + ExceptionUtils.getStackTrace(e));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//捕获异常后进行回滚
            return new Result(false, "出现异常！" + e.getMessage());
        }
    }

    @PostMapping(value = "/deleteJob")
    public Result deleteJob(JobInfo jobInfo) {
        try {
            jobInfoService.deleteById(jobInfo.getJobId());
            scheduler.jobDelete(jobInfo.getJobName(), jobInfo.getJobGroup());
            return new Result(true, "删除成功！");
        } catch (Exception e) {
            log.error("删除定时任务失败：" + ExceptionUtils.getStackTrace(e));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//捕获异常后进行回滚
            return new Result(false, "删除失败！" + e.getMessage());
        }
    }


}
